<template>
  <div class="create-account-box">
  <div class="page-header">
    <h2 class="page-title">
      {{ isEditing ? '编辑账号信息' : '账号寄售/租赁信息填写' }}
    </h2>
    <p class="page-subtitle">{{ isEditing ? '修改账号信息，完成后点击更新按钮' : '请完整填写以下信息，以便快速完成账号交易' }}</p>
  </div>
  <div class="create-account-page">
    <div class="form-container">
      <a-spin :spinning="loadingAccountData" tip="加载账号数据中...">
        <a-form
        :model="accountForm"
        @finish="createAccount"
        layout="vertical"
        :rules="formRules"
        ref="formRef"
      >
        <!-- 基础资产信息卡片 -->
        <div class="card-content">
          <h2 class="card-title">
            <i class="iconfont icon-zuanshi_o"></i> 基础资产信息
          </h2>
          <a-row :xs="[1]">
            <!-- 响应式栅格，手机端单列 -->
            <a-col :xs="24" :md="24">
              <div class="form-content-item">
                <div class="form-content-item-title required">登录区选项</div>
                <a-form-item label="" name="server">
                  <div class="login-center-group">
                    <div
                      :class="[
                        'level-box-login',
                        accountForm.server === 'QQ'
                          ? 'level-box-selected'
                          : 'level-box-unselected',
                      ]"
                      @click="accountForm.server = 'QQ'"
                    >
                      QQ
                    </div>
                    <div
                      :class="[
                        'level-box-login',
                        accountForm.server === '微信'
                          ? 'level-box-selected'
                          : 'level-box-unselected',
                      ]"
                      @click="accountForm.server = '微信'"
                    >
                      微信
                    </div>
                    <div
                      :class="[
                        'level-box-login',
                        accountForm.server === 'Steam'
                          ? 'level-box-selected'
                          : 'level-box-unselected',
                      ]"
                      @click="accountForm.server = 'Steam'"
                    >
                      Steam
                    </div>
                  </div>
                </a-form-item>
              </div>
            </a-col>
          </a-row>
          <a-col :xs="24" :md="24">
            <div class="form-content-item">
              <div class="form-content-item-title required">登录方式</div>
              <a-form-item label="" name="loginMethod">
                <div class="login-method-grid">
                  <div
                    :class="[
                      'login-method-card',
                      accountForm.loginMethod === '账密登录'
                        ? 'login-method-selected'
                        : '',
                    ]"
                    @click="accountForm.loginMethod = '账密登录'"
                  >
                    <span class="login-method-badge">推荐</span>
                    <div class="login-method-icon">
                      <i class="iconfont icon-key"></i>
                    </div>
                    <div class="login-method-title">账密登录</div>
                  </div>

                  <div
                    :class="[
                      'login-method-card',
                      accountForm.loginMethod === '扫码登录'
                        ? 'login-method-selected'
                        : '',
                    ]"
                    @click="accountForm.loginMethod = '扫码登录'"
                  >
                    <div class="login-method-icon">
                      <i class="iconfont icon-ico"></i>
                    </div>
                    <div class="login-method-title">扫码登录</div>
                  </div>
                </div>
                <p class="form-tip" style="margin-bottom: 0;">
                  温馨提示:
                  <a style="color: red"
                    >账密登录的商品价格会提高一个等级，售出速度提高3倍</a
                  >，租客上号更加方便，避免您不在线无法登录。平台收取押金保证账号安全，也可在腾讯安全中心选择禁止登录某些游戏。
                </p>
              </a-form-item>
            </div>
          </a-col>

          <!-- 账密登录时显示账号密码字段 -->
          <a-row v-if="accountForm.loginMethod === '账密登录'" :gutter="[16, 16]">
            <a-col :xs="24" :sm="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">游戏账号</div>
                <a-form-item label="" name="gameUsername">
                  <a-input
                    v-model:value="accountForm.gameUsername"
                    placeholder="请输入游戏账号"
                    style="width: 100%"
                  />
                </a-form-item>
              </div>
            </a-col>
            <a-col :xs="24" :sm="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">游戏密码</div>
                <a-form-item label="" name="gamePassword">
                  <a-input
                    v-model:value="accountForm.gamePassword"
                    type="password"
                    placeholder="请输入游戏密码"
                  />
                </a-form-item>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">总资仓(M)</div>
                <a-form-item label="" name="totalAssets">
                  <a-input-number
                    v-model:value="accountForm.totalAssets"
                    :min="0"
                    style="width: 100%"
                    placeholder="请输入总资仓(M)"
                    :formatter="
                      (value) =>
                        `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                    "
                    :parser="(value) => value.replace(/\$\s?|(,*)|(M)/g, '')"
                  />
                </a-form-item>
                <p class="form-tip">
                  温馨提示:
                  总资仓为仓库内所有资产的总和，包括收藏品等，这些不作为价格考量。
                </p>
              </div>
            </a-col>

            <a-col :xs="24" :sm="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">纯币资产(M)</div>
                <a-form-item label="" name="coinAssets">
                  <a-input-number
                    v-model:value="accountForm.coinAssets"
                    :min="0"
                    style="width: 100%"
                    placeholder="请输入纯币资产(M)"
                    :formatter="
                      (value) =>
                        `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                    "
                    :parser="(value) => value.replace(/\$\s?|(,*)|(M)/g, '')"
                  />
                  <div class="form-tip">
                    出售时只计算纯哈弗币的数值，可以变卖仓库内物资提高哈弗币总额<br />纯币小于20M无法寄售租赁，
                    6套、红蛋、咖啡豆等可保留。
                  </div>
                </a-form-item>
              </div>
            </a-col>

            <a-col :xs="24" :sm="12" :md="8">
              <div class="form-content-item">
                <div class="form-content-item-title required">安全箱</div>
                <a-form-item label="" name="safetyBox">
                  <a-select
                    v-model:value="accountForm.safetyBox"
                    placeholder="请选择安全箱类型"
                    :auto-fit-input-width="false"
                  >
                    <a-select-option value="顶级安全箱 (3x3)"
                      >顶级安全箱 (3x3)</a-select-option
                    >
                    <a-select-option value="高级安全箱 (2x3)"
                      >高级安全箱 (2x3)</a-select-option
                    >
                    <a-select-option value="进阶安全箱 (2x2)"
                      >进阶安全箱 (2x2)</a-select-option
                    >
                    <a-select-option value="基础安全箱 (1x2)"
                      >基础安全箱 (1x2)</a-select-option
                    >
                  </a-select>
                  <p class="form-tip">
                    温馨提示: 保险箱低于6格影响回收价，9格定价最高
                  </p>
                </a-form-item>
              </div>
            </a-col>
            <a-col :xs="24" :md="8" :sm="8">
              <div class="form-content-item">
                <div class="form-content-item-title required">
                  体力/训练中心等级
                </div>
                <a-form-item label="" name="energyLevel">
                  <div class="level-box-group">
                    <div
                      v-for="i in [7, 6, 5, 4, 3]"
                      :key="i"
                      :class="[
                        'level-box',
                        accountForm.energyLevel === i
                          ? 'level-box-selected'
                          : 'level-box-unselected',
                      ]"
                      @click="accountForm.energyLevel = i"
                    >
                      {{ i }}
                    </div>
                  </div>
                </a-form-item>
              </div>
            </a-col>

            <a-col :xs="24" :md="8" :sm="8">
              <div class="form-content-item">
                <div class="form-content-item-title required">负重等级</div>
                <a-form-item label="" name="weightLevel">
                  <div class="level-box-group">
                    <div
                      v-for="i in [7, 6, 5, 4, 3]"
                      :key="i"
                      :class="[
                        'level-box',
                        accountForm.weightLevel === i
                          ? 'level-box-selected'
                          : 'level-box-unselected',
                      ]"
                      @click="accountForm.weightLevel = i"
                    >
                      {{ i }}
                    </div>
                  </div>
                </a-form-item>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="12" :md="6">
              <div class="form-content-item">
                <div class="form-content-item-title">AWM子弹数量</div>
                <a-form-item label="" name="awmBullets">
                  <a-input-number
                    v-model:value="accountForm.awmBullets"
                    :min="0"
                    style="width: 100%"
                    :placeholder="`${priceConfig.awmBulletPrice}r/发，不填默认为0`"
                  />
                </a-form-item>
              </div>
            </a-col>

            <a-col :xs="24" :sm="12" :md="6">
              <div class="form-content-item">
                <div class="form-content-item-title">六级子弹数量</div>
                <a-form-item label="" name="level6Bullets">
                  <a-input-number
                    v-model:value="accountForm.level6Bullets"
                    :min="0"
                    style="width: 100%"
                    :placeholder="`${priceConfig.level6BulletPrice}r/发，0即表示不出`"
                  />
                </a-form-item>
              </div>
            </a-col>

            <a-col :xs="24" :sm="12" :md="6">
              <div class="form-content-item">
                <div class="form-content-item-title">六级甲数量</div>
                <a-form-item label="" name="level6A">
                  <a-input-number
                    v-model:value="accountForm.level6A"
                    :min="0"
                    style="width: 100%"
                    :placeholder="`${priceConfig.level6ArmorPrice}r/套，用多少计算多少`"
                  />
                </a-form-item>
              </div>
            </a-col>

            <a-col :xs="24" :sm="12" :md="6">
              <div class="form-content-item">
                <div class="form-content-item-title">咖啡豆数量</div>
                <a-form-item label="" name="coffeeBeans">
                  <a-input-number
                    v-model:value="accountForm.coffeeBeans"
                    :min="0"
                    style="width: 100%"
                    :placeholder="`${priceConfig.coffeeBeanPrice}r/颗，租客打完后结算`"
                  />
                </a-form-item>
              </div>
            </a-col>
          </a-row>

        <!-- 账号信息卡片 -->
          <h2 class="card-title" style="margin-top: 0; padding-top: 0;">
            <i class="iconfont icon-wode"></i> 账号信息
          </h2>
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :md="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">段位</div>
                <a-form-item label="" name="rank">
                  <a-select
                    v-model:value="accountForm.rank"
                    placeholder="请选择段位"
                    :auto-fit-input-width="false"
                  >
                    <a-select-option value="白银">白银</a-select-option>
                    <a-select-option value="黄金">黄金</a-select-option>
                    <a-select-option value="铂金">铂金</a-select-option>
                    <a-select-option value="钻石">钻石</a-select-option>
                    <a-select-option value="黑鹰">黑鹰</a-select-option>
                    <a-select-option value="三角洲巅峰">三角洲巅峰</a-select-option>
                  </a-select>
                </a-form-item>
              </div>
            </a-col>
            <a-col :xs="24" :md="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">账号等级</div>
                <a-form-item label="" name="level">
                  <a-input-number
                    v-model:value="accountForm.level"
                    :min="30"
                    :max="60"
                    style="width: 100%"
                    placeholder="请输入账号等级（最低30级）"
                  />
                  <p class="form-tip">温馨提示: 账号等级低于30无法寄售租赁</p>
                </a-form-item>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :md="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">干员外观</div>
                <a-form-item label="" name="appearance">
                  <div class="appearance-grid">
                    <div
                      v-for="item in [
                        '默认外观',
                        '稀有外观',
                        '史诗外观',
                        '传说外观',
                        '限定外观',
                        '其他',
                      ]"
                      :key="item"
                      :class="[
                        'appearance-card',
                        accountForm.appearance === item
                          ? 'appearance-selected'
                          : 'appearance-unselected',
                      ]"
                      @click="accountForm.appearance = item"
                    >
                      {{ item }}
                    </div>
                  </div>
                  <p class="form-tip">温馨提示: 请选择干员外观</p>
                </a-form-item>
              </div>
            </a-col>
            <a-col :xs="24" :md="12">
              <div class="form-content-item">
                <div class="form-content-item-title">持有刀皮（多选）</div>
                <a-form-item label="" name="weaponSkins">
                  <a-checkbox-group
                    v-model:value="accountForm.weaponSkins"
                    class="weapon-skins-group"
                  >
                    <a-checkbox value="赤霄" class="weapon-skin-checkbox"
                      >赤霄</a-checkbox
                    >
                    <a-checkbox value="怜悯" class="weapon-skin-checkbox"
                      >怜悯</a-checkbox
                    >
                    <a-checkbox value="影锋" class="weapon-skin-checkbox"
                      >影锋</a-checkbox
                    >
                    <a-checkbox value="黑海" class="weapon-skin-checkbox"
                      >黑海</a-checkbox
                    >
                    <a-checkbox value="北极星" class="weapon-skin-checkbox"
                      >北极星</a-checkbox
                    >
                  </a-checkbox-group>
                  <p class="form-tip">温馨提示: 持有刀皮可以加快被租的速度哦</p>
                </a-form-item>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :md="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">账号记录</div>
                <a-form-item label="" name="accountRecord">
                  <a-radio-group v-model:value="accountForm.accountRecord">
                    <a-radio value="无封禁记录">无封禁记录</a-radio>
                    <a-radio value="有封号记录">有封号记录</a-radio>
                  </a-radio-group>
                </a-form-item>
              </div>
            </a-col>
            <a-col :xs="24" :md="12">
              <div class="form-content-item">
                <div class="form-content-item-title required">人脸是否本人</div>
                <a-form-item label="" name="face">
                  <a-radio-group v-model:value="accountForm.face">
                    <a-radio value="是">是</a-radio>
                    <a-radio value="否">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </div>
            </a-col>
          </a-row>

        <!-- 交易信息卡片 -->
          <h2 class="card-title" style="margin-top: 0; padding-top: 0;"><i class="iconfont icon-wode"></i>交易信息</h2>

          <a-row :gutter="[16, 16]">
            <a-col :xs="24">
              <div class="form-content-item">
                <div class="form-content-item-title required">账号截图</div>
                <a-form-item label="" name="image">
                  <div class="image-upload-wrapper" :class="{ 'login-required': !userStore.isLoggedIn }">
                    <ImageUpload
                      v-model:value="accountForm.image"
                      placeholder-text="上传账号截图(总资产、仓库最重要)"
                      @change="handleImageChange"
                    />
                    <div 
                      v-if="!userStore.isLoggedIn" 
                      class="login-mask"
                      @click="handleLoginMaskClick"
                    >
                      <div class="login-mask-content">
                        <!-- <i class="iconfont icon-lock"></i> -->
                        <!-- <span>请先登录后上传图片</span> -->
                      </div>
                    </div>
                  </div>
                </a-form-item>
              </div>
            </a-col>
          </a-row>
          <a-row :gutter="[16, 16]">
            <a-col :xs="24">
              <div class="form-content-item">
                <div class="form-content-item-title">备注</div>
                <div class="quick-remark-grid">
                  <div
                    v-for="opt in quickRemarkOptions"
                    :key="opt.key"
                    class="quick-remark-card"
                    @click="addQuickRemark(opt.text)"
                  >
                    {{ opt.title }}
                  </div>
                </div>
                <a-form-item label="" name="remark">
                  <a-textarea
                    v-model:value="accountForm.remark"
                    :rows="4"
                    placeholder="请输入备注信息（可选）"
                    :maxlength="500"
                    show-count
                  />
                </a-form-item>
              </div>
            </a-col>
          </a-row>
      </div>


        <!-- 提交按钮 -->
        <div class="form-actions form-actions-with-user floating-submit">
          <div class="user-summary" v-if="userStore.userInfo">
            <i class="iconfont icon-wode" />
            <span class="user-name">{{
              userStore.userInfo.username || userStore.userInfo.phone
            }}</span>
          </div>
          <div class="price-summary" v-if="calculatedPrice.totalPrice > 0">
            <div class="price-item">
              <span class="label">纯币价格：</span>
              <span class="price">¥{{ calculatedPrice.totalPrice }}</span>
            </div>
            <div class="price-item">
              <span class="label">物品价格：</span>
              <span class="price">¥{{ calculatedPrice.itemValue }}</span>
            </div>
            <!-- <div class="price-item">
              <span class="label">出号纯币：</span>
              <span class="price">¥{{ calculatedPrice.sellPrice }}</span>
            </div>
            <div class="price-item">
              <span class="label">出号物品价格：</span>
              <span class="price">¥{{ calculatedPrice.sellItemValue }}</span>
            </div> -->
            <!-- <div class="price-item">
              <span class="label">押金：</span>
              <span class="price">¥{{ calculatedPrice.deposit }}</span>
              <span class="auth-status" :class="{ 'verified': calculatedPrice.isUserVerified, 'unverified': !calculatedPrice.isUserVerified }">
                ({{ calculatedPrice.isUserVerified ? '已认证' : '未认证' }})
              </span>
            </div> -->
            <!-- <div class="price-item">
              <span class="label">当前比例：</span>
              <span class="price">{{ calculatedPrice.ratio }}</span>
            </div> -->
          </div>
          <a-button
            type="primary"
            html-type="submit"
            :loading="loading"
            size="large"
            class="submit-button"
          >
            {{ loading ? (isEditing ? "更新中..." : "创建中...") : (isEditing ? "更新账号" : "发布账号") }}
          </a-button>
        </div>
        </a-form>
      </a-spin>
    </div>
  </div>
  
  <!-- 登录/注册模态框 -->
  <a-modal v-model:open="loginVisible" title="用户登录" :footer="null" width="400px">
    <LoginForm @switch-to-register="switchToRegister" @success="handleLoginSuccess"/>
  </a-modal>

  <a-modal v-model:open="registerVisible" title="用户注册" :footer="null" width="400px">
    <RegisterForm @switch-to-login="switchToLogin" @success="handleLoginSuccess" />
  </a-modal>
</div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
import accountAPI from "~/api/account";
import ImageUpload from "~/components/ImageUpload.vue";
import LoginForm from "~/components/LoginForm.vue";
import RegisterForm from "~/components/RegisterForm.vue";
import { useUserStore } from "~/stores/user";
import { PriceConfigService } from "~/api/config";

const route = useRoute();
const router = useRouter();

const userStore = useUserStore();
if (process.client && !userStore.userInfo) {
  userStore.restoreUserData();
}

// 确保获取最新的用户信息（包含认证状态）
if (process.client && userStore.userInfo && !userStore.userInfo.isVerified) {
  userStore.getUserInfo();
}

const quickRemarkOptions = [
  {
    key: "onlyCoin",
    title: "只卖纯币，其余不动",
    text: "只卖纯币，其余都不动",
  },
  {
    key: "collectiblesKeep1",
    title: "可以用卡片",
    text: "可以用卡片",
  },
  {
    key: "collectiblesKeep",
    title: "收藏品不动",
    text: "收藏品不动",
  },
  {
    key: "materialsAsIs",
    title: "六套/子弹/咖啡豆按数量结算",
    text: "六套、子弹、咖啡豆用多少算多少",
  },
];

function addQuickRemark(text) {
  const current = accountForm.remark?.trim();
  if (!current) {
    accountForm.remark = text;
    return;
  }
  // 去重追加
  if (!current.includes(text)) {
    accountForm.remark = `${current}${
      current.endsWith("。") || current.endsWith(".") ? "" : "。"
    }${text}`;
  }
}

// 编辑模式
const editingAccountId = ref(route.query.id || null);
const isEditing = computed(() => !!editingAccountId.value);
const loadingAccountData = ref(false);

// 表单引用
const formRef = ref();

// 表单数据
const accountForm = reactive({
  server: "QQ",
  loginMethod: "账密登录",
  gameUsername: "", // 游戏账号
  gamePassword: "", // 游戏密码
  rank: "白银",
  totalAssets: null,
  coinAssets: null,
  level: null,
  energyLevel: 7,
  weightLevel: 7,
  awmBullets: null,
  level6A: null,
  level6Bullets: null,
  coffeeBeans: null,
  appearance: "默认外观",
  weaponSkins: [],
  accountRecord: "无封禁记录",
  face: "是",
  safetyBox: "顶级安全箱 (3x3)",
  image: [],
  remark: "",
});

// 表单验证规则
const formRules = {
  server: [{ required: true, message: "请选择区服" }],
  loginMethod: [{ required: true, message: "请选择登录方式" }],
  gameUsername: [
    {
      validator: (_r, v) => {
        if (accountForm.loginMethod === "账密登录" && !v) {
          return Promise.reject("请输入游戏账号");
        }
        return Promise.resolve();
      },
      trigger: "change",
    },
  ],
  gamePassword: [
    {
      validator: (_r, v) => {
        if (accountForm.loginMethod === "账密登录" && !v) {
          return Promise.reject("请输入游戏密码");
        }
        return Promise.resolve();
      },
      trigger: "change",
    },
  ],
  rank: [{ required: true, message: "请选择段位" }],
  totalAssets: [{ required: true, message: "请输入总资仓(M)" }],
  coinAssets: [
    { required: true, message: "请输入纯币资产(M)" },
    {
      validator: (_r, v) =>
        v >= 20 ? Promise.resolve() : Promise.reject("纯币资产不能小于20M"),
    },
  ],
  level: [
    { required: true, message: "请输入等级" },
    {
      validator: (_r, v) =>
        v >= 30 ? Promise.resolve() : Promise.reject("账号等级不能低于30"),
    },
  ],
  energyLevel: [{ required: true, message: "请选择体力等级" }],
  weightLevel: [{ required: true, message: "请选择负重等级" }],
  awmBullets: [{ required: false, message: "请输入AWM子弹数量" }],
  level6A: [{ required: false, message: "请输入六级甲数量" }],
  level6Bullets: [{ required: false, message: "请输入六级子弹数量" }],
  coffeeBeans: [{ required: false, message: "请输入咖啡豆数量" }],
  appearance: [{ required: true, message: "请选择干员外观" }],
  accountRecord: [{ required: true, message: "请选择账号记录" }],
  face: [{ required: true, message: "请选择是否本人" }],
  safetyBox: [{ required: true, message: "请选择安全箱类型" }],
  image: [
    {
      validator: (_r, v) => {
        if (!v || v.length < 3) {
          return Promise.reject("请上传三张截图，仓库、总资产、特勤处");
        }
        return Promise.resolve();
      },
      trigger: "change",
    },
  ],
};

// 加载状态
const loading = ref(false);

// 价格配置
const priceConfig = ref({
  baseRatio: 35,
  awmBulletPrice: 1.0,
  level6ArmorPrice: 3.5,
  level6BulletPrice: 0.5,
  coffeeBeanPrice: 0.8,
  sellRatioDiff: 5
});

// 计算属性
const calculatedRatio = computed(() => {
  if (
    accountForm.totalAssets &&
    accountForm.coinAssets &&
    accountForm.coinAssets > 0
  ) {
    const ratio = Math.round(accountForm.totalAssets / accountForm.coinAssets);
    return `1:${ratio}`;
  }
  return "1:1";
});

/*********************************
计算函数 计算收号价格
根据PRD文档：
- 默认比例: 35
- 基础安全箱 (1x2): 固定比例 36
- 进阶安全箱 (2x2): 能量等级7时比例34，其他情况35
- 高级安全箱 (2x3): 能量等级7时比例33，其他情况34
- 顶级安全箱 (3x3): 能量等级7时比例32，其他情况33
- 账密登录: 在原有基础上比例减1
- 纯币价格（￥）计算: 纯币资产（M）* 100 / 对应比例

物品价值计算：
- 物品价值 = AWM子弹*1块钱 + 六套 * 3.5块钱 + 六级子弹 * 0.5元 + 咖啡豆 * 0.8

出号规则：
- 比例在收号基础上减少5
- 物品价值收取20%手续费
*********************************/

const calculatedPrice = computed(() => {
  if (accountForm.coinAssets) {
    // 1. 计算收号比例 - 使用配置化的基础比例
    const config = priceConfig.value;
    let buyRatio = config.baseRatio;

    if (accountForm.safetyBox.includes("基础安全箱 (1x2)")) {
      buyRatio = config.baseRatio + 1; // 基础保险箱固定比例 +1
    } else if (accountForm.safetyBox.includes("进阶安全箱 (2x2)")) {
      buyRatio = accountForm.energyLevel === 7 ? config.baseRatio - 1 : config.baseRatio;
    } else if (accountForm.safetyBox.includes("高级安全箱 (2x3)")) {
      buyRatio = accountForm.energyLevel === 7 ? config.baseRatio - 2 : config.baseRatio - 1;
    } else if (accountForm.safetyBox.includes("顶级安全箱 (3x3)")) {
      buyRatio = accountForm.energyLevel === 7 ? config.baseRatio - 3 : config.baseRatio - 2;
    }
    
    // 账密登录的比例在原有基础上减1
    if (accountForm.loginMethod === "账密登录") {
      buyRatio = buyRatio - 1;
    }

    // 2. 计算纯币价格 - 使用 Math.round 保持和服务端一致
    const coinPrice = Math.round((Number(accountForm.coinAssets) * 100) / buyRatio);

    // 3. 计算物品价值 - 使用配置化的价格参数
    const awmBulletsValue = (accountForm.awmBullets || 0) * config.awmBulletPrice;
    const level6AValue = (accountForm.level6A || 0) * config.level6ArmorPrice;
    const level6BulletsValue = (accountForm.level6Bullets || 0) * config.level6BulletPrice;
    const coffeeBeansValue = (accountForm.coffeeBeans || 0) * config.coffeeBeanPrice;
    
    const itemValue = Math.round(awmBulletsValue + level6AValue + level6BulletsValue + coffeeBeansValue);

    // 4. 计算总价格
    const totalPrice = coinPrice;

    // 5. 计算出号价格 - 使用配置化的比例差值
    const sellRatio = buyRatio - config.sellRatioDiff;
    const sellCoinPrice = Math.round((Number(accountForm.coinAssets) * 100) / sellRatio);
    const sellItemValue = Math.round(itemValue * 1.2); // 物品价值收取20%手续费
    const sellPrice = sellCoinPrice;
    // const sellPrice = sellCoinPrice + sellItemValue;

    // 6. 计算押金 - 使用 Math.round 保持和服务端一致
    const isUserVerified = userStore.userInfo?.isVerified || false;
    const deposit = isUserVerified
      ? Math.round(sellPrice * 0.3) // 认证用户押金30%
      : Math.round(sellPrice * 0.8); // 未认证用户押金80%

    return {
      coinPrice: coinPrice,
      itemValue: itemValue,
      totalPrice: totalPrice,
      sellPrice: sellPrice,
      sellItemValue: sellItemValue,
      deposit: deposit,
      isUserVerified: isUserVerified,
      ratio: buyRatio, // 添加比例信息用于调试
    };
  }
  return {
    coinPrice: 0,
    itemValue: 0,
    totalPrice: 0,
    sellPrice: 0,
    sellItemValue: 0,
    deposit: 0,
    isUserVerified: false,
    ratio: 0,
  };
});

// 获取账号数据进行编辑
const fetchAccountForEdit = async () => {
  if (!editingAccountId.value) return;
  
  loadingAccountData.value = true;
  try {
    const res = await accountAPI.getAccount(editingAccountId.value);
    if (res.code === 200 && res.data) {
      const data = res.data;
      
      // 填充表单数据
      Object.keys(accountForm).forEach(key => {
        if (data.hasOwnProperty(key)) {
          accountForm[key] = data[key];
        }
      });
      
      // 特殊处理图片字段
      if (data.image) {
        try {
          const images = typeof data.image === 'string' ? JSON.parse(data.image) : data.image;
          accountForm.image = Array.isArray(images) ? images : [images];
        } catch (e) {
          accountForm.image = Array.isArray(data.image) ? data.image : [data.image];
        }
      }
      
      // 特殊处理刀皮字段
      if (data.weaponSkins) {
        accountForm.weaponSkins = Array.isArray(data.weaponSkins) ? data.weaponSkins : [];
      }
      
    } else {
      message.error(res.message || '获取账号信息失败');
      router.push('/accounts/create');
    }
  } catch (error) {
    console.error('获取账号信息失败:', error);
    message.error('获取账号信息失败');
    router.push('/accounts/create');
  } finally {
    loadingAccountData.value = false;
  }
};

// 图片上传处理
const handleImageChange = (val) => {
  accountForm.image = Array.isArray(val) ? val : val ? [val] : [];
};

// 创建或更新账号
const createAccount = async () => {
  try {
    loading.value = true;

    // 表单验证
    await formRef.value.validate();

    // 准备提交数据，处理可选字段
    const submitData = { ...accountForm };

    // 将null值转换为undefined，确保后端验证能正确处理
    const optionalFields = ['awmBullets', 'level6A', 'level6Bullets', 'coffeeBeans'];
    optionalFields.forEach(field => {
      if (submitData[field] === null || submitData[field] === '') {
        delete submitData[field]; // 删除空值字段，让后端使用默认值
      }
    });

    let res;
    if (isEditing.value) {
      // 调用API更新账号
      res = await accountAPI.updateAccount(editingAccountId.value, submitData);
    } else {
      // 调用API创建账号
      res = await accountAPI.createAccount(submitData);
    }

    if (res.status === "success" || res.code === 200) {
      message.success(isEditing.value ? "账号更新成功！" : "账号创建成功！");
      // 跳转到我的账号页面
      router.push("/user/profile?tab=accounts");
    } else {
      message.error(res.message || (isEditing.value ? "更新失败" : "创建失败"));
    }
  } catch (error) {
    console.error(isEditing.value ? "更新账号失败:" : "创建账号失败:", error);
    message.error(isEditing.value ? "更新失败，请检查表单信息" : "创建失败，请检查表单信息");
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 返回首页
const goHome = () => {
  router.push('/');
};

// 处理登录遮罩点击
const handleLoginMaskClick = () => {
  message.info('请先登录后再上传图片');
  showLoginModal();
};

// 显示登录模态框
const showLoginModal = () => {
  loginVisible.value = true;
  registerVisible.value = false;
};

// 切换到注册
const switchToRegister = () => {
  loginVisible.value = false;
  registerVisible.value = true;
};

// 切换到登录
const switchToLogin = () => {
  registerVisible.value = false;
  loginVisible.value = true;
};

// 处理登录成功
const handleLoginSuccess = () => {
  loginVisible.value = false;
  registerVisible.value = false;
  message.success('登录成功！现在可以上传图片了');
};

// 登录模态框状态
const loginVisible = ref(false);
const registerVisible = ref(false);

// 加载价格配置
const loadPriceConfig = async () => {
  try {
    const config = await PriceConfigService.getPriceConfig();
    priceConfig.value = config;
  } catch (error) {
    console.error('加载价格配置失败:', error);
    // 使用默认配置，不显示错误信息给用户
  }
};

// 页面加载时，加载配置和账号数据
onMounted(async () => {
  // 并行加载配置和账号数据
  const promises = [loadPriceConfig()];
  
  if (isEditing.value) {
    promises.push(fetchAccountForEdit());
  }
  
  await Promise.all(promises);
});
</script>

<style lang="scss" scoped>
.create-account-box {
  @media (max-width: 768px) {
    padding: 0 10px;
    background-origin: border-box;
  }
}
.create-account-page {
  width: 100%;
  max-width: 1024px;
  margin: 0 auto;
  padding: 16px;
  box-sizing: border-box;
  border-width: 2px;

  .form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    line-height: 1.5;
  }

  .form-container {
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03),
      0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02);
    border-radius: 16px;
    border-width: 2px;
    background-color: #fff;

    .card-title {
      display: flex;
      align-items: center;
      min-height: 48px;
      margin-bottom: 16px;
      padding-top: 20px;
      color: rgba(0, 0, 0, 0.88);
      font-size: 22px;

      i {
        color: #165dff;
        margin-right: 8px;
        font-size: 24px;
      }
    }

    .card-content {
      padding: 0 16px;
      box-sizing: border-box;
      margin-bottom: 16px;
      gap: 16px;
    }

    .quick-remark-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
      gap: 8px;
      margin-bottom: 8px;
    }

    .quick-remark-card {
      @extend .appearance-card;
      text-align: center;
      padding: 6px 8px;
      font-weight: 600;
      font-size: 14px;
    }

    .form-content-item {
      box-sizing: border-box;
      border-width: 2px;
      margin-bottom: 16px;

      .form-content-item-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 10px;
        position: relative;
        display: inline-block;
      }

      .required {
        position: relative;
      }

      .required::before {
        content: "*";
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        border-width: 2px;
        color: #ef4444;
        position: absolute;
        right: -16px;
        top: 2px;
      }
    }

    /* 通用可选卡片基础样式，合并重复规则 */
    .level-box-login,
    .level-box,
    .appearance-card,
    .login-method-card {
      border: 1px solid #e5e7eb;
      border-radius: 12px;
      border-width: 2px;
      cursor: pointer;
      transition: all 0.2s ease;
      user-select: none;
      background: #fff;
    }

    /* 统一选中态样式 */
    .level-box-selected,
    .appearance-selected,
    .login-method-selected {
      border-color: #165dff;
      border-width: 2px;
      background: rgba(22, 93, 255, 0.08);
      color: #165dff;
    }

    /* 统一悬浮态样式（未选中时） */
    .level-box-unselected:hover,
    .appearance-card:hover,
    .login-method-card:hover {
      border-color: #165dff;
      border-width: 2px;
      font-size: 16px;
      background: rgba(22, 93, 255, 0.05);
    }

    /* 登录区选项 - 自定义样式 */
    .login-center-group {
      display: flex;
      gap: 8px;
    }

    .level-box-login {
      flex: 1;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 700;
    }

    .level-box-unselected {
      border-color: #e5e7eb;
      border-width: 2px;
      background: #ffffff;
      color: #333333;
    }

    /* 等级方块 - 自定义样式 */
    .level-box-group {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .level-box {
      width: 48px;
      height: 48px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 700;
      color: #000;
    }

    /* 干员外观 - 卡片网格样式 */
    .appearance-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
      gap: 8px;
    }

    .appearance-card {
      padding: 12px 10px;
      text-align: center;
      font-weight: 1200;
      font-size: 14px;
    }

    /* 登录方式 - 卡片样式 */
    .login-method-grid {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 12px;
    }

    .login-method-card {
      position: relative;
      padding: 0 12px;
      height: 48px;
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .login-method-icon {
      width: 32px;
      height: 32px;
      border-radius: 9999px;
      border-width: 2px;
      background: rgba(22, 93, 255, 0.1);
      color: #165dff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
    }

    .login-method-badge {
      position: absolute;
      top: 8px;
      right: 8px;
      background: #10b981;
      color: #fff;
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 9999px;
      border-width: 2px;
    }

    .login-method-title {
      font-weight: 600;
    }

    /* 刀皮选择样式 */
    .weapon-skins-group {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      border-width: 2px;
    }

    .weapon-skin-checkbox {
      margin-bottom: 8px;
    }

    /* 统一输入控件高度 */
    :deep(.ant-input:not(textarea)) {
      height: 48px !important;
      line-height: 48px !important;
      padding-top: 0 !important;
      padding-bottom: 0 !important;
      font-size: 14px;
    }

    :deep(.ant-input-number) {
      height: 48px;
    }

    :deep(.ant-input-number .ant-input-number-input) {
      height: 48px !important;
      line-height: 48px !important;
      padding-top: 0 !important;
      padding-bottom: 0 !important;
      font-size: 14px;
    }

    :deep(.ant-select-selector) {
      height: 48px !important;
      min-height: 48px !important;
      align-items: center !important;
    }

    :deep(.ant-select-single .ant-select-selector .ant-select-selection-item),
    :deep(
        .ant-select-single
          .ant-select-selector
          .ant-select-selection-placeholder
      ) {
      line-height: 48px !important;
      font-size: 16px;
      border-width: 2px;
    }

    :deep(.ant-select-selection-search-input) {
      height: 48px !important;
    }

    :deep(.ant-textarea) {
      font-size: 14px;
    }

    /* 单选和复选框样式优化 */
    :deep(.ant-radio-wrapper),
    :deep(.ant-checkbox-wrapper) {
      border-width: 2em;
    }
  }

  .form-actions {
    text-align: right;
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    border-width: 2px;
  }

  /* 悬浮提交按钮样式 */
  .floating-submit {
    position: sticky;
    bottom: 0;
    background: white;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    border-top: 1px solid #e8e8e8;
    margin-top: 16px;
  }

  .form-actions-with-user {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }

  .user-summary {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #666;
    font-size: 14px;
  }

  .user-name {
    font-weight: 600;
    color: #333;
  }

  .price-summary {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: #666;
    font-size: 14px;
  }

  .price-summary .price {
    color: #10b981;
    font-weight: 700;
    font-size: 16px;
  }

  .price-item {
    margin-right: 16px;
    white-space: nowrap;
  }

  .price-item:last-child {
    margin-right: 0;
  }

  @media (max-width: 768px) {
    .price-item {
      margin-right: 8px;
      font-size: 12px;
    }

    .price-item .label {
      font-size: 12px;
    }

    .price-item .price {
      font-size: 14px;
    }
  }

  .submit-button {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
  }

  /* 认证状态样式 */
  .auth-status {
    font-size: 12px;
    margin-left: 4px;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 500;
  }

  .auth-status.verified {
    color: #10b981;
    background-color: rgba(16, 185, 129, 0.1);
  }

  .auth-status.unverified {
    color: #f59e0b;
    background-color: rgba(245, 158, 11, 0.1);
  }
}

/* 移动端特定样式 */
@media (max-width: 768px) {
  .create-account-page {
    padding: 0px;
  }

  .form-container .card-title {
    padding: 0 12px;
    min-height: 44px;
    font-size: 16px;
  }

  .form-container .card-content {
    padding: 0 12px;
  }

  .form-content-item {
    margin-bottom: 12px !important;
  }

  .form-content-item .form-content-item-title {
    font-size: 14px;
    margin-bottom: 8px;
  }

  /* 卡片尺寸调整 */
  // .level-box-login,
  // .level-box,
  // .login-method-card {  }

  /* 缩小间距 */
  .a-row {
    margin-bottom: 8px !important;
  }

  /* 调整标签提示大小 */
  .form-tip {
    font-size: 11px !important;
  }

  /* 调整按钮区域布局 */
  .form-actions-with-user {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  /* 移动端悬浮按钮优化 */
  .floating-submit {
    padding: 12px;
  }

  /* 优化图片上传组件 */
  :deep(.image-upload-container) {
    padding: 12px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 360px) {
  .appearance-grid,
  .quick-remark-grid {
    grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  }

  .appearance-card,
  .quick-remark-card {
    font-size: 12px !important;
    padding: 6px 4px;
  }

  .level-box {
    width: 40px !important;
    height: 40px !important;
    font-size: 14px;
  }
}

/* 页面头部样式 */
.page-header {
  text-align: center;
  padding: 28px 16px 16px;
}

.page-title {
  font-size: 40px;
  margin: 0 0 8px;
  color: black;
  font-weight: 600;
}

.page-subtitle {
  color: #fff;
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
}

/* 移动端页面头部适配 */
@media (max-width: 768px) {
  .page-header {
    padding: 20px 12px 12px;
  }
  
  .page-title {
    font-size: 24px;
    margin-bottom: 6px;
  }
  
  .page-subtitle {
    font-size: 14px;
  }
}

/* 小屏幕进一步优化 */
@media (max-width: 480px) {
  .page-header {
    padding: 6rem 0px;
  }
  
  .page-title {
    font-size: 28px;
    margin-bottom: 4px;
  }
  
  .page-subtitle {
    font-size: 13px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 360px) {
  .page-title {
    font-size: 18px;
  }
  
  .page-subtitle {
    font-size: 12px;
  }
}

/* 图片上传遮罩样式 */
.image-upload-wrapper {
  position: relative;
  
  &.login-required {
    .login-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      // background: rgba(255, 255, 255, 0.1);
      // backdrop-filter: blur(4px);
      // -webkit-backdrop-filter: blur(4px);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      z-index: 10;
      border-radius: 8px;
      transition: all 0.3s ease;
      
      // &:hover {
      //   background: rgba(255, 255, 255, 0.95);
      //   backdrop-filter: blur(6px);
      //   -webkit-backdrop-filter: blur(6px);
      // }
      
      .login-mask-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
        padding: 24px;
        color: #666;
        text-align: center;
        
        i {
          font-size: 32px;
          color: #1890ff;
          opacity: 0.8;
        }
        
        span {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }
      }
    }
  }
}

/* 移动端遮罩适配 */
@media (max-width: 768px) {
  .image-upload-wrapper.login-required .login-mask {
    .login-mask-content {
      padding: 20px;
      gap: 10px;
      
      i {
        font-size: 28px;
      }
      
      span {
        font-size: 14px;
      }
    }
  }
}

/* 小屏幕遮罩适配 */
@media (max-width: 480px) {
  .image-upload-wrapper.login-required .login-mask {
    .login-mask-content {
      padding: 16px;
      gap: 8px;
      
      i {
        font-size: 24px;
      }
      
      span {
        font-size: 13px;
      }
    }
  }
}
</style>